package com.zq.qq2;


import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class CodeUtils {


    private static Map<String, String> getLianZongParamMap() {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("user_name", SharedPreferenceUtil.getInstance().getLianZongUser());
        paramMap.put("user_pw", SharedPreferenceUtil.getInstance().getLianZongPwd());
        // 填写用户名和密码
        paramMap.put("yzm_minlen", "4");
        paramMap.put("yzm_maxlen", "4");
        paramMap.put("yzmtype_mark", "0");
        paramMap.put("zztool_token", "7e76d37c86314067552981f89af31cd7");
        return paramMap;
    }

    private static Map<String, String> getYunMaParamMap() {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("username", SharedPreferenceUtil.getInstance().getYunmaUser());
        paramMap.put("password", SharedPreferenceUtil.getInstance().getYunmaPwd());
        // 填写用户名和密码
        paramMap.put("codetype", "1004");
        paramMap.put("appid", "1");
        paramMap.put("appkey", "22cc5376925e9387a23cf797cb9ba745");
        paramMap.put("timeout", "60");
        paramMap.put("method", "upload");
        return paramMap;
    }

    public static int cutPNG(InputStream input,
                             OutputStream out,
                             int x, int y, int width, int height, boolean isPinBan) throws Exception {
        try {
            BitmapDrawable bmpDraw = new BitmapDrawable(input);
            Bitmap bmp = bmpDraw.getBitmap();
            Bitmap scaledBitmap;
            scaledBitmap = Bitmap.createBitmap(bmp, x, y, width, height);
            if (isPinBan)
                scaledBitmap = Toturn(scaledBitmap);
            scaledBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.close();
            int px = scaledBitmap.getPixel(90, 40);
            scaledBitmap.recycle();
            return px;

        } catch (Exception e) {
            Constant.Debug("失败:" + e.getMessage());
        }
        return 0;
    }

    public static Bitmap Toturn(Bitmap img) {
        Matrix matrix = new Matrix();
        matrix.postRotate(90);
        int width = img.getWidth();
        int height = img.getHeight();
        img = Bitmap.createBitmap(img, 0, 0, width, height, matrix, true);
        return img;
    }

    public static String getCode(boolean yzm) {
        String filePath = "/mnt/sdcard/qq_code.png";//本地验证码图片路径
        String url;
        Map<String, String> paramMap;
        Constant.Debug("开始上传验证码");
        if (yzm) {
            url = "http://bbb4.hyslt.com/api.php?mod=php&act=upload";
            paramMap = getLianZongParamMap();
            String ret = Upload(url, paramMap, "upload", filePath);
            try {
                JSONObject jsonObject = new JSONObject(ret);
                if (jsonObject.getBoolean("result"))
                    return jsonObject.getJSONObject("data").getString("val");

            } catch (Exception e) {
            }
        } else {
            url = "http://api.yundama.com/api.php";
            paramMap = getYunMaParamMap();
            String ret = Upload(url, paramMap, "file", filePath);
            if (ret.equals(""))
                return "";
            try {
                JSONObject jsonObject = new JSONObject(ret);
                url = "http://api.yundama.com/api.php?cid=%s&method=result";
                url = String.format(url, jsonObject.get("cid"));
                int i = 1;
                do {
                    Thread.sleep(1000);
                    if (i++ > 15)
                        break;
                    ret = HttpGet(url);
                    jsonObject = new JSONObject(ret);
                    ret = jsonObject.getString("text");
                    if (ret == null || ret.equals(""))
                        continue;
                    return ret;
                } while (true);
            } catch (Exception e) {

            }

        }
        return "";
    }

    public final static String HttpGet(String surl) {
        try {
            URL url = new URL(surl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);
            connection.connect();

            InputStream in = connection.getInputStream();
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            while (true) {
                int rc = in.read(buf);
                if (rc <= 0) {
                    break;
                } else {
                    bout.write(buf, 0, rc);
                }
            }
            in.close();
            return new String(bout.toByteArray(), "UTF-8");
        } catch (Exception e) {

        }
        return "";
    }

    public final static String Upload(String surl, Map<String, String> paramMap, String fileName, String filePath) {
        String BOUNDARY = "---------------------------68163001211748";
        try {
            URL url = new URL(surl);
            Constant.Debug(surl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + BOUNDARY);
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(15000);
            // 普通参数
            OutputStream out = new DataOutputStream(connection.getOutputStream());
            if (paramMap != null) {

                StringBuffer strBuf = new StringBuffer();
                Iterator<Map.Entry<String, String>> iter = paramMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry<String, String> entry = iter.next();
                    String inputName = entry.getKey();
                    String inputValue = entry.getValue();
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\""
                            + inputName + "\"\r\n\r\n");
                    strBuf.append(inputValue);
                }
                out.write(strBuf.toString().getBytes());
            }
            if (filePath != null) {
                File file = new File(filePath);
                String filename = file.getName();
                String contentType = "image/png";//这里看情况设置
                StringBuffer strBuf = new StringBuffer();
                strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                strBuf.append("Content-Disposition: form-data; name=\""
                        + fileName + "\"; filename=\"" + filename + "\"\r\n");
                strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                out.write(strBuf.toString().getBytes());
                DataInputStream in = new DataInputStream(
                        new FileInputStream(file));
                int bytes = 0;
                byte[] bufferOut = new byte[1024];
                while ((bytes = in.read(bufferOut)) != -1) {
                    out.write(bufferOut, 0, bytes);
                }
                in.close();
            }
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();

            InputStream in = connection.getInputStream();
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            while (true) {
                int rc = in.read(buf);
                if (rc <= 0) {
                    break;
                } else {
                    bout.write(buf, 0, rc);
                }
            }
            in.close();
            //结果输出
            return (new String(bout.toByteArray()));
        } catch (Exception e) {

        }
        return "";
    }

    private final static String HttpPost(String surl, Map<String, String> paramMap) {
        String BOUNDARY = "---------------------------68163001211748";
        try {
            URL url = new URL(surl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + BOUNDARY);
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(20000);
            // 普通参数
            OutputStream out = new DataOutputStream(connection.getOutputStream());
            if (paramMap != null) {
                StringBuffer strBuf = new StringBuffer();
                Iterator<Map.Entry<String, String>> iter = paramMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry<String, String> entry = iter.next();
                    String inputName = entry.getKey();
                    String inputValue = entry.getValue();
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\""
                            + inputName + "\"\r\n\r\n");
                    strBuf.append(inputValue);
                }
                out.write(strBuf.toString().getBytes());
            }
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();

            InputStream in = connection.getInputStream();
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            while (true) {
                int rc = in.read(buf);
                if (rc <= 0) {
                    break;
                } else {
                    bout.write(buf, 0, rc);
                }
            }
            in.close();
            //结果输出
            return (new String(bout.toByteArray()));
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    public final static String Money(int index) {
        String[] url = new String[]{
                "http://bbb4.hyslt.com/api.php?mod=php&act=point",
                "http://api.yundama.com/api.php?method=balance"
        };
        Map<String, String> paramMap = new HashMap<>();
        if (index == 0) {
            paramMap.put("user_name", SharedPreferenceUtil.getInstance().getLianZongUser());
            paramMap.put("user_pw", SharedPreferenceUtil.getInstance().getLianZongPwd());
        } else {
            paramMap.put("username", SharedPreferenceUtil.getInstance().getYunmaUser());
            paramMap.put("password", SharedPreferenceUtil.getInstance().getYunmaPwd());
            paramMap.put("appid", "2215");
            paramMap.put("appkey", "2170f4eadbb80b47179a03cb17556b93");
            paramMap.put("method", "balance");
        }
        String ret = HttpPost(url[index], paramMap);
        if (ret.equals("")) {
            return "余额:未成功获取";
        }
        try {
            JSONObject js = new JSONObject(ret);
            if (index == 0) {
                return "余额:" + js.get("data");
            } else {
                return "余额:" + js.get("balance");
            }
        } catch (Exception e) {

        }
        return "余额:数据获取失败";
    }

}